package com.example.gatewayservice.controller;

import com.example.gatewayservice.config.GatewayConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/gateway/users")
public class GatewayController {
    @Autowired
    private GatewayConfig gatewayConfig;

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping(value = { "", "/{id}" }, method = { RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE })
    public ResponseEntity<?> routeToUserService(HttpServletRequest request, @PathVariable(required = false) Long id, @RequestBody(required = false) Object body) {
        String userServiceUrl = gatewayConfig.getRoutes().get("user-service");
        String requestPath = id != null ? "/api/users/" + id : "/api/users";
        String targetUrl = userServiceUrl + requestPath;

        HttpMethod method = HttpMethod.valueOf(request.getMethod());
        HttpEntity<?> httpEntity = new HttpEntity<>(body);

        return restTemplate.exchange(targetUrl, method, httpEntity, Object.class);
    }
}